package deng.quartz;

import java.util.Arrays;
import java.util.Properties;

import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Load a Quartz service that configured as proxy (client) that perform list, add or delelet job
 * to an actual server that it connects to via RMI.
 * 
 * Usage: java QuartzClient <quartz-client.properties> [listjob]
 * Usage: java QuartzClient <quartz-client.properties> addjob <name> <delay>
 * Usage: java QuartzClient <quartz-client.properties> deletejob <name>
 */
public class QuartzClient
{
	/** A slf4j logger. */
	private static Logger logger = LoggerFactory.getLogger(QuartzClient.class);
	private QuartzService quartzService;
	private String cmd;
	private String[] cmdArgs;
	
	public QuartzClient(String[] args)
	{
		initInstance(args);
	}
	private void initInstance(String[] args)
	{
		logger.debug("Init with args: " + Arrays.asList(args));
		
		// Init the quartzService with first args.
		Properties props = Utils.loadProperties(args[0]);
		try {
			StdSchedulerFactory schedulerFactory = new StdSchedulerFactory(props);
			Scheduler scheduler = schedulerFactory.getScheduler();
			logger.debug("Creating quartzService with " + scheduler);
			quartzService = new QuartzService();
			quartzService.setScheduler(scheduler);
		} catch (SchedulerException e) {
			throw new RuntimeException(e);
		}
		
		// Parse out the rest of args
		if (args.length > 1) {
			cmd = args[1];
			cmdArgs = Arrays.copyOfRange(args, 2, args.length);
		} else {
			cmd = "listjob";
		}
	}

	public void run()
	{
		logger.debug("Running Quartz as RMI Client for cmd: " + cmd);
		if (cmd.equals("listjob")) {
			logger.debug("List all triggers and jobs.");
			quartzService.logAllTiggersAndJobs();
		} else if (cmd.equals("addjob")) {
			logger.debug("Adding a new job.");
			String name = cmdArgs[0];
			long delay = Long.parseLong(cmdArgs[1]);
			quartzService.addJob(name, delay);
		} else if (cmd.equals("deletejob")) {
			logger.debug("Delete a new job.");
			String name = cmdArgs[0];
			quartzService.deleteJob(name);
		} else {
			throw new RuntimeException("Unknown cmd: " + cmd);
		}
	}

	public static void main(String[] args)
	{
		QuartzClient main = new QuartzClient(args);
		main.run();
	}

}
